// 全局变量存储截屏数据
let currentScreenshotData = null;

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.removeAll(function () {
    const title = chrome.i18n.getMessage("copy_to_siyuan");
    chrome.contextMenus.create({
      id: "copy-to-siyuan",
      title: title,
      contexts: ["selection", "image"],
    });
  });
  // 移除keepAlive消息，因为service worker不需要保持连接
  // setInterval(() => {
  //   chrome.runtime.sendMessage({ type: "keepAlive" });
  // }, 30000);
});

// 截屏函数
async function takeScreenshot(tabId) {
  try {
    console.log("开始截屏，标签页ID:", tabId);

    // 首先检查标签页是否存在
    const tab = await chrome.tabs.get(tabId);
    if (!tab) {
      throw new Error("标签页不存在");
    }

    console.log("标签页信息:", tab.url);

    // 使用chrome.tabs.captureVisibleTab截取当前可见区域
    const dataUrl = await chrome.tabs.captureVisibleTab(null, {
      format: "png",
      quality: 100,
    });

    if (!dataUrl) {
      throw new Error("无法获取截屏数据");
    }

    console.log("截屏成功，数据URL长度:", dataUrl.length);

    const timestamp = new Date()
      .toISOString()
      .replace(/[:.]/g, "-")
      .slice(0, 19);
    const filename = `screenshot_${timestamp}.png`;

    // 将data URL转换为Blob
    const response = await fetch(dataUrl);
    const blob = await response.blob();

    console.log("Blob大小:", blob.size, "类型:", blob.type);

    // 转换为Base64
    const base64 = await new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });

    console.log("Base64转换成功，长度:", base64.length);

    return {
      success: true,
      filename: filename,
      data: base64,
      type: blob.type,
    };
  } catch (error) {
    console.error("截屏过程中出错:", error);
    throw error;
  }
}

chrome.contextMenus.onClicked.addListener(function (info, tab) {
  if (info.menuItemId === "copy-to-siyuan") {
    chrome.tabs.sendMessage(tab.id, {
      func: "copy",
      tabId: tab.id,
      srcUrl: info.srcUrl,
    });
  }
});

// 添加模板渲染函数
function renderTemplate(template, data) {
  return template.replace(/\${([^}]+)}/g, function (match, key) {
    // 检查是否为条件表达式
    const conditionalMatch = key.match(/(.+?)\s*\?\s*(.*?)\s*:\s*(.*)/);
    if (conditionalMatch) {
      const conditionKey = conditionalMatch[1].trim();
      const trueValueString = conditionalMatch[2].trim();
      const falseValueString = conditionalMatch[3].trim();

      const condition = conditionKey
        .split(".")
        .reduce((obj, prop) => obj && obj[prop], data);

      // 辅助函数，用于解析值中的变量或字符串
      const getValue = (valueStr) => {
        if (
          (valueStr.startsWith("'") && valueStr.endsWith("'")) ||
          (valueStr.startsWith('"') && valueStr.endsWith('"'))
        ) {
          return valueStr.slice(1, -1); // 字符串字面量
        }
        // 尝试解析为变量
        const parts = valueStr.split("+").map((part) => part.trim());
        let result = "";
        for (const part of parts) {
          if (
            (part.startsWith("'") && part.endsWith("'")) ||
            (part.startsWith('"') && part.endsWith('"'))
          ) {
            result += part.slice(1, -1);
          } else {
            const variableValue = part
              .split(".")
              .reduce((obj, prop) => obj && obj[prop], data);
            result += variableValue !== undefined ? variableValue : "";
          }
        }
        return result;
      };

      if (condition) {
        return getValue(trueValueString);
      } else {
        return getValue(falseValueString);
      }
    } else {
      // 普通变量替换
      const value = key
        .split(".")
        .reduce((obj, prop) => obj && obj[prop], data);
      return value !== undefined ? value : "";
    }
  });
}

// 获取当前日期时间格式化函数
function getDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  let month = now.getMonth() + 1;
  let day = now.getDate();
  let hour = now.getHours();
  let minute = now.getMinutes();
  let second = now.getSeconds();
  if (month.toString().length === 1) {
    month = "0" + month;
  }
  if (day.toString().length === 1) {
    day = "0" + day;
  }
  if (hour.toString().length === 1) {
    hour = "0" + hour;
  }
  if (minute.toString().length === 1) {
    minute = "0" + minute;
  }
  if (second.toString().length === 1) {
    second = "0" + second;
  }
  return (
    year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
  );
}

// 获取简单日期时间
function getSimpleDateTime() {
  const now = new Date();
  const date = now.toISOString().slice(0, 10);
  const time = now.toTimeString().slice(0, 5);
  return { date, time };
}

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  // 处理getScreenshot消息
  if (request.action === "getScreenshot") {
    sendResponse(currentScreenshotData);
    return;
  }

  if (request.func !== "upload-copy") {
    return;
  }

  const requestData = request.data;
  const fetchFileErr = requestData.fetchFileErr;
  const dom = requestData.dom;
  let files = requestData.files;

  let screenshotMarkdown = "";

  // 先进行截屏
  try {
    console.log("准备进行截屏...");
    screenshotData = await takeScreenshot(requestData.tabId);
    if (screenshotData.success) {
      console.log("截屏成功，文件名:", screenshotData.filename);
      console.log("截屏数据类型:", screenshotData.type);
      console.log("截屏数据前100字符:", screenshotData.data.substring(0, 100));
      console.log("截屏数据总长度:", screenshotData.data.length);

      // 存储截屏数据供content script使用
      currentScreenshotData = screenshotData;

      // === 新增：上传截屏图片到 /api/asset/upload ===
      if (screenshotData && screenshotData.success) {
        function base64ToBlob(base64, mime) {
          const byteString = atob(base64.split(",")[1]);
          const ab = new ArrayBuffer(byteString.length);
          const ia = new Uint8Array(ab);
          for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
          }
          return new Blob([ab], { type: mime });
        }
        try {
          const formData = new FormData();
          formData.append("assetsDirPath", "/assets/");
          const filename =
            screenshotData.filename ||
            "screenshot_" + new Date().getTime() + ".png";
          const blob = base64ToBlob(
            screenshotData.data,
            screenshotData.type || "image/png"
          );
          formData.append("file[]", blob, filename);
          await fetch(requestData.api + "/api/asset/upload", {
            method: "POST",
            headers: {
              Authorization: "Token " + requestData.token,
            },
            body: formData,
          })
            .then((resp) => resp.json())
            .then((uploadJson) => {
              if (uploadJson.code === 0) {
                const succMap = uploadJson.data.succMap;
                const errFiles = uploadJson.data.errFiles;
                console.log("截屏上传成功:", succMap, "失败文件:", errFiles);
                const assetPath = succMap[filename];
                if (assetPath) {
                  screenshotAssetPath = assetPath;
                  screenshotMarkdown = `![截屏](${assetPath})\n\n`;
                }
              } else {
                console.error("截屏上传失败:", uploadJson.msg);
              }
            })
            .catch((e) => {
              console.error("截屏上传异常:", e);
            });
        } catch (e) {
          console.error("截屏上传异常:", e);
        }
      }
      // === 新增结束 ===
    }
  } catch (error) {
    console.error("截屏失败:", error);
    // 截屏失败不影响剪藏流程
  }

  // 将页面的 html 中的图片上传
  const formData = new FormData();

  for (const key of Object.keys(files)) {
    const data = files[key].data;
    console.log("处理文件:", key, "数据长度:", data.length);
    try {
      const base64Response = await fetch(data);
      const blob = await base64Response.blob();
      formData.append(key, blob);
      // console.log('文件已添加到FormData:', key, 'blob大小:', blob.size);
    } catch (error) {
      console.error("处理文件失败:", key, error);
    }
  }
  formData.append("notebook", requestData.notebook);
  formData.append("parentID", requestData.parentDoc);
  formData.append("parentHPath", requestData.parentHPath);
  formData.append("href", requestData.href);
  formData.append("tags", requestData.tags);
  formData.append("clipType", requestData.type);
  // 修复：将正文内容加入 formData
  if (requestData.dom) {
    formData.append("dom", requestData.dom);
  }
  // 调用剪藏接口
  fetch(requestData.api + "/api/extension/copy", {
    method: "POST",
    headers: {
      Authorization: "Token " + requestData.token,
    },
    body: formData,
  })
    .then((response) => {
      console.log("上传响应状态:", response.status, response.statusText);
      if (response.redirected) {
        chrome.tabs
          .sendMessage(requestData.tabId, {
            func: "tipKey",
            msg: "tip_token_invalid",
            tip: "tip",
          })
          .catch((error) => {
            console.warn("发送消息失败:", error);
          });
      }

      return response.json();
    })
    .then((response) => {
      console.log("上传响应数据:", response);
      if (response.code < 0) {
        chrome.tabs
          .sendMessage(requestData.tabId, {
            func: "tip",
            msg: response.msg,
            tip: requestData.tip,
          })
          .catch((error) => {
            console.warn("发送消息失败:", error);
          });
        return;
      }

      chrome.tabs
        .sendMessage(requestData.tabId, {
          func: "copy2Clipboard",
          data: response.data && response.data.md ? response.data.md : "", // 防御 null
        })
        .catch((error) => {
          console.warn("发送消息失败:", error);
        });

      if ("" !== response.msg && requestData.type !== "article") {
        chrome.tabs
          .sendMessage(requestData.tabId, {
            func: "tip",
            msg: response.msg,
            tip: requestData.tip,
          })
          .catch((error) => {
            console.warn("发送消息失败:", error);
          });
      }

      if (requestData.type === "article") {
        let title = requestData.title ? requestData.title : "Untitled";
        title = title.replaceAll("/", "");
        chrome.storage.sync.get(
          {
            clipTemplate:
              '---\n\n- ${title}${siteName ? " - " + siteName : ""}\n- [${urlDecoded}](${url}) \n- ${excerpt}\n- ${date} ${time}\n\n---\n\n${screenshot}${content}',
          },
          (items) => {
            let excerpt = requestData.excerpt.trim();
            if ("" !== excerpt) {
              // 将连续的三个换行符替换为两个换行符
              excerpt = excerpt.replace(/\n{3,}/g, "\n\n");
              // 从第二行开始，每行前面加两个空格 https://github.com/siyuan-note/siyuan/issues/11315
              excerpt = excerpt.replace(/\n/g, "\n  ");
              excerpt = excerpt.trim();
            }
            let urlDecoded = requestData.href;
            try {
              urlDecoded = decodeURIComponent(urlDecoded);
            } catch (e) {
              console.warn(e);
            }

            const { date, time } = getSimpleDateTime();

            const templateData = {
              title: requestData.title || "Untitled",
              siteName: requestData.siteName || "",
              excerpt: excerpt || "",
              url: requestData.href,
              urlDecoded: urlDecoded,
              date,
              time,
              tags: requestData.tags,
              content:
                response.data && response.data.md ? response.data.md : "", // 防御 null
              screenshot: screenshotMarkdown, // 插入截屏 markdown
            };

            // 渲染模板
            let markdown;
            try {
              markdown = renderTemplate(items.clipTemplate, templateData);
            } catch (e) {
              console.error("Template rendering error:", e);
              // 如果模板渲染失败，使用默认格式
              markdown = getDefaultMarkdown(
                requestData,
                response.data.md,
                screenshotData
              );
            }

            // 添加格式化，每个空行换称两个空行，去除行首的空格
            markdown = markdown.replace(/^[\s]+/gm, "").replace(/\n/g, "\n\n");

            console.log("markdown:", markdown);

            // 调用接口根据markdown创建文档
            fetch(requestData.api + "/api/filetree/createDocWithMd", {
              method: "POST",
              headers: {
                Authorization: "Token " + requestData.token,
              },
              body: JSON.stringify({
                notebook: requestData.notebook,
                parentID: requestData.parentDoc,
                tags: requestData.tags,
                path: requestData.parentHPath + "/" + title,
                markdown: markdown,
                withMath:
                  response.data && response.data.withMath
                    ? response.data.withMath
                    : false,
                clippingHref: requestData.href,
                listDocTree: requestData.listDocTree,
              }),
            })
              .then((response) => {

                console.log("下载到本地");
                // 同步下载md文件到本地
                // 生成文件名
                // 文件名称修改为网站标题 + 时间
                const filename = `${requestData.title}.md`;

                // 创建Blob对象
                const blob = new Blob([markdown], { type: "text/markdown" });

                // 在background script中，我们需要使用data URL而不是URL.createObjectURL
                const reader = new FileReader();
                reader.onload = function() {
                  const dataUrl = reader.result;
                  
                  // 使用Chrome下载API下载文件
                  chrome.downloads.download(
                    {
                      url: dataUrl,
                      filename: filename,
                      saveAs: false, // 让用户选择保存位置
                    },
                    (downloadId) => {
                      if (chrome.runtime.lastError) {
                        console.error("下载失败:", chrome.runtime.lastError);
                      } else {
                        console.log("下载成功，下载ID:", downloadId);
                      }
                    }
                  );
                };
                reader.readAsDataURL(blob);
                return response.json();
              })
              .then((response) => {
                if (0 === response.code) {
                  console.log("response", response);

                  chrome.tabs
                    .sendMessage(requestData.tabId, {
                      func: "tipKey",
                      msg: "tip_clip_ok",
                      tip: requestData.tip,
                    })
                    .catch((error) => {
                      console.warn("发送消息失败:", error);
                    });

                  // 检查是否需要打开文档
                  chrome.storage.sync.get(
                    {
                      expOpenAfterClip: false,
                    },
                    (items) => {
                      if (items.expOpenAfterClip && response.data) {
                        // 使用 SiYuan 协议在桌面应用中打开文档
                        const documentUrl = `siyuan://blocks/${response.data}`;
                        chrome.tabs.create({ url: documentUrl });
                      }
                    }
                  );

                  if (fetchFileErr) {
                    // 可能因为跨域问题导致下载图片失败，这里调用内核接口 `网络图片转换为本地图片` https://github.com/siyuan-note/siyuan/issues/7224
                    fetch(requestData.api + "/api/format/netImg2LocalAssets", {
                      method: "POST",
                      headers: {
                        Authorization: "Token " + requestData.token,
                      },
                      body: JSON.stringify({
                        id: response.data,
                        url: requestData.href, // 改进浏览器剪藏扩展转换本地图片成功率 https://github.com/siyuan-note/siyuan/issues/7464
                      }),
                    });
                  }

                  chrome.tabs
                    .sendMessage(requestData.tabId, {
                      func: "reload",
                    })
                    .catch((error) => {
                      console.warn("发送消息失败:", error);
                    });

                  // 清理截屏数据
                  currentScreenshotData = null;
                } else {
                  chrome.tabs
                    .sendMessage(requestData.tabId, {
                      func: "tip",
                      msg: response.msg,
                      tip: requestData.tip,
                    })
                    .catch((error) => {
                      console.warn("发送消息失败:", error);
                    });
                }
              });

            //
          }
        );
      }
    })
    .catch((e) => {
      console.error(e);
      chrome.tabs
        .sendMessage(requestData.tabId, {
          func: "tipKey",
          msg: "tip_siyuan_kernel_unavailable",
          tip: "tip",
        })
        .catch((error) => {
          console.warn("发送消息失败:", error);
        });

      // 清理截屏数据
      currentScreenshotData = null;
    });
});

// 默认剪藏格式的处理函数（当模板渲染失败时使用）
function getDefaultMarkdown(requestData, contentMd, screenshotData) {
  let markdown = "---\n\n* " + (requestData.title || "Untitled");
  const siteName = requestData.siteName;
  if ("" !== siteName) {
    markdown += " - " + siteName;
  }
  markdown += "\n";
  const href = requestData.href;
  let linkText = href;
  try {
    linkText = decodeURIComponent(linkText);
  } catch (e) {
    console.warn(e);
  }
  markdown += "* " + "[" + linkText + "](" + href + ")\n";
  let excerpt = requestData.excerpt.trim();
  if ("" !== excerpt) {
    // 将连续的三个换行符替换为两个换行符
    excerpt = excerpt.replace(/\n{3,}/g, "\n\n");
    // 从第二行开始，每行前面加两个空格 https://github.com/siyuan-note/siyuan/issues/11315
    excerpt = excerpt.replace(/\n/g, "\n  ");
    excerpt = excerpt.trim();
    markdown += "* " + excerpt + "\n";
  } else {
    markdown += "\n";
  }
  markdown += "* " + getDateTime() + "\n\n---\n\n";

  // 添加截屏
  if (screenshotData && screenshotData.success) {
    markdown += `![截屏](./${screenshotData.filename})\n\n`;
  }


  markdown += contentMd;

  return markdown;
}
